package com.happyfarmhelper.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import com.happyfarmhelper.vo.FarmlandStatus;
import com.happyfarmhelper.vo.Seed;
import com.happyfarmhelper.vo.User;

public class CommUtils {
	
	private static Log log = LogFactory.getLog(CommUtils.class);
		
	public static String getInputStream(InputStream inputStream, boolean addNewline) {
		StringBuffer buffer = new StringBuffer();
		BufferedReader bufferReader;
		String line;
		try {
			bufferReader = new BufferedReader(new InputStreamReader(
					inputStream, HTTP.UTF_8));
			line = bufferReader.readLine();
			while (line != null) { // 如果 line 为空说明读完了
				buffer.append(line); // 将读到的内容添加到 buffer 中
				if (addNewline) {
					buffer.append("\n"); // 添加换行符
				}
//				System.out.println(line);
				line = bufferReader.readLine(); // 读取下一行
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}
	
	public static List<Header> initHeaders() {
		List<Header> headers = new ArrayList<Header>();
		
		headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7"));
		headers.add(new BasicHeader("Accept", "	text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
		headers.add(new BasicHeader("Accept-Language", "zh-cn,zh;q=0.5"));
		headers.add(new BasicHeader("Accept-Encoding", "*"));
		headers.add(new BasicHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7"));
		headers.add(new BasicHeader("Keep-Alive", "300"));
		headers.add(new BasicHeader("Connection", "Keep-Alive"));

		return headers;
	}
	
	public static String getMD5Str(String str) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");

			messageDigest.reset();

			messageDigest.update(str.getBytes("UTF-8"));

		} catch (NoSuchAlgorithmException e) {
			log.info("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}

		return md5StrBuff.toString();
	}
	
	public static Map<String, Object> getFarmlandStatusFromJsonSting(InputStream inputStream) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<FarmlandStatus> farmlandStatusList = new ArrayList<FarmlandStatus>();
		User owner = new User();
		JSONObject jsonObject = JSONObject.fromObject(getInputStream(inputStream, false));
		JSONArray farmlandStatusArray = jsonObject.getJSONArray("farmlandStatus");
		if(farmlandStatusArray == null || farmlandStatusArray.size() == 0) {
			return null;
		}
		// 得到每块地的FarmlandStatus
		for(int i = 0; i < farmlandStatusArray.size(); i++) {
			JSONObject farmlandJsonObject = farmlandStatusArray.getJSONObject(i);
			FarmlandStatus farmlandStatus = new FarmlandStatus();
			farmlandStatus.setPlantId(((Integer)farmlandJsonObject.get("a")).intValue());
			farmlandStatus.setGrowthStage(((Integer)farmlandJsonObject.get("b")).intValue());
			farmlandStatus.setWeed(((Integer)farmlandJsonObject.get("f")).intValue());
			farmlandStatus.setWorm(((Integer)farmlandJsonObject.get("g")).intValue());
			farmlandStatus.setHumidity(((Integer)farmlandJsonObject.get("h")).intValue());
//			int output = ((Integer)farmlandJsonObject.get("k")).intValue();//产量
			int minimalResidual = ((Integer)farmlandJsonObject.get("l")).intValue();//最小剩余量
			int residual = ((Integer)farmlandJsonObject.get("m")).intValue();//剩余量
			farmlandStatus.setCanScrounge(residual > minimalResidual);
			farmlandStatus.setScrounged(((Integer)farmlandJsonObject.get("n")).intValue() == 1);
			farmlandStatus.setPlantTime(((Integer)farmlandJsonObject.get("q")).intValue());
			farmlandStatus.setBug(((Integer)farmlandJsonObject.get("t")).intValue());
			farmlandStatusList.add(farmlandStatus);
		}
		
		map.put("farmlandStatusList", farmlandStatusList);
		// 得到User的信息
		if(jsonObject.has("user")){
			JSONObject userJsonObject = jsonObject.getJSONObject("user");
			owner = new User();
			owner.setUserId(((Integer)userJsonObject.get("uId")).intValue());
			owner.setUserName(userJsonObject.get("userName").toString());
			owner.setMoney(((Integer)userJsonObject.get("money")).intValue());
			owner.setFB(Integer.parseInt(userJsonObject.get("FB").toString()));
			owner.setExp(Integer.parseInt(userJsonObject.get("exp").toString()));
			owner.setCharm(Integer.parseInt(userJsonObject.get("charm").toString()));
			owner.setHeadPic(userJsonObject.get("headPic").toString());
		}
		map.put("owner", owner);
		
		return map;
	}
	
	public static List<User> getFriendsFromJsonString(InputStream inputStream) {
		List<User> friendsList = new ArrayList<User>();
		String jasonStr = getInputStream(inputStream, false);
		log.info(jasonStr);
		if(jasonStr.length() < 15){
			log.info("Get Friends Error!");
			return null;
		}
		JSONObject jsonObject = JSONObject.fromObject(jasonStr);
		JSONArray friendsArray = jsonObject.getJSONArray("data");
		if(friendsArray == null || friendsArray.size() == 0) {
			return null;
		}
		User[] friends = new User[friendsArray.size()];
		
		for(int i = 0; i < friendsArray.size(); i++) {
			JSONObject fridendsJsonObject = friendsArray.getJSONObject(i);
			User friend = new User();
			friend.setUserId(((Integer)fridendsJsonObject.get("userId")).intValue());
			friend.setUserName(((String)fridendsJsonObject.get("userName")));
			friend.setMoney(Integer.parseInt(fridendsJsonObject.get("money").toString()));
			if(fridendsJsonObject.containsKey("FB")){
				friend.setFB(Integer.parseInt((String)fridendsJsonObject.get("FB")));
			}
			friend.setExp(Integer.parseInt(fridendsJsonObject.get("exp").toString()));
			friend.setCharm(Integer.parseInt(fridendsJsonObject.get("charm").toString()));
			friend.setHeadPic(fridendsJsonObject.get("headPic").toString());
			friends[i] = friend;
		}
		Arrays.sort(friends, new Comparator<User>() {
			public int compare(User o1, User o2) {
				User user1 = (User)o1;
				User user2 = (User)o2;
				return user2.getExp() - user1.getExp();
			}
		});
		for(User friend : friends){
			friendsList.add(friend);
		}
		return friendsList;
	}
	
	public static String getMsgFromJsonString(InputStream inputStream) {
		String jasonStr = getInputStream(inputStream, false);
		log.info(jasonStr);
		StringBuffer sb = new StringBuffer();
		JSONObject jsonObject = JSONObject.fromObject(jasonStr);
		int farmIndex = ((Integer)jsonObject.get("farmlandIndex")).intValue();
		sb.append("  第").append(farmIndex).append("块:");
		int code = ((Integer)jsonObject.get("code")).intValue();
		if(code == 0){
			if(jsonObject.containsKey("direction")) {
				sb.append(jsonObject.get("direction"));
			}
		} else {
			if(jsonObject.containsKey("direction")) {
				if("".equals(jsonObject.get("direction"))){
					sb.append("Operation Success!");
				} else {
					sb.append(jsonObject.get("direction"));
				}
			}
		}
		
		return sb.toString();
	}
	
	public static Map<String, Seed> getSeedsMapFromJsonString(InputStream inputStream) {
		Map<String, Seed> seedsMap = new HashMap<String, Seed>();
		JSONObject jsonObject = JSONObject.fromObject(getInputStream(inputStream, false));
		JSONArray seedsArray = jsonObject.getJSONArray("1");
		if(seedsArray == null || seedsArray.size() == 0) {
			return null;
		}
		for(int i = 0; i < seedsArray.size(); i++) {
			JSONObject seedsJsonObject = seedsArray.getJSONObject(i);
			Seed seed = new Seed();
			seed.setSeedId(((Integer)seedsJsonObject.get("cId")).intValue());
			seed.setSeedName(((String)seedsJsonObject.get("cName")).replace("种子", ""));
			seed.setGrowthCycle(Integer.parseInt(seedsJsonObject.get("growthCycle").toString()));
			seedsMap.put(String.valueOf(seed.getSeedId()), seed);
		}
		return seedsMap;
	}
	
	public static String getInterval(double interval) {
		double hours = Math.floor(interval / 3600);
		double minutes = Math.floor(interval % 3600 / 60);
		double seconds = interval % 3600 % 60;
		return String.format("%02d", (int)hours) + ":" + String.format("%02d", (int)minutes) + ":" + String.format("%02d", (int)seconds);
	}
	
	public static String showCalendar(){
		Calendar cal = Calendar.getInstance();
		int hour = cal.get(Calendar.HOUR_OF_DAY);
		int minute = cal.get(Calendar.MINUTE);
		int second = cal.get(Calendar.SECOND);
		return String.format("%02d", hour) + ":" + String.format("%02d", minute) + ":" + String.format("%02d", second);
	}
}
